package top.qitun.controller;

import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;

import io.jsonwebtoken.lang.Collections;
import top.qitun.bizz.oss.resource.entity.ResourceBO;
import top.qitun.bizz.oss.resource.service.ResourceService;
import top.qitun.model.response.ObjectCollectionResponse;
import top.qitun.util.DateUtil;

//@RefreshScope
@Controller
@RequestMapping(value = "/v1")
@ConfigurationProperties(prefix = "oss")
public class OssController {
	Logger logger = LoggerFactory.getLogger(getClass());

	private String accessKeyId = "Sq3VArArISFZolo3";
	private String accessKeySecret = "jCqkj9xOyQhccha2GmeHVZcNaIOtix";
	private String endPoint = "oss-cn-shenzhen.aliyuncs.com";
	private String bucketName = "xinglantou-test";
	private String imgServer = "http://xinglantou-test.img-cn-shenzhen.aliyuncs.com";
	@Autowired
	private ResourceService resourceService;
	
	@RequestMapping(value = "/picupload", method = RequestMethod.POST)
	@ResponseBody
	public ObjectCollectionResponse<ResourceBO> upload(HttpServletRequest request) {
		logger.debug("enter the oss upload method!");
		try {
			List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("upfile");
			List<ResourceBO> resourceList = files.stream().map(file ->ossUpload(file))
					.collect(Collectors.toList());
//			List<Resource> resourceList = Stream.of(files).map(file ->ossUpload(file))
//					.collect(Collectors.toList());
			ObjectCollectionResponse<ResourceBO> result = new ObjectCollectionResponse<>(0, "", resourceList);
			return result;
		} catch (Exception e) {
			logger.error("图片上传出错，", e);
			return new ObjectCollectionResponse<>(-1, "图片上传失败,请联系系统管理员");
		}
	}
	
//	@RequestMapping(value = "/picupload", method = RequestMethod.POST)
//	@ResponseBody
//	public ObjectCollectionResponse<ResourceBO> upload(@RequestParam("files") MultipartFile[] files) {
//		logger.debug("enter the oss upload method!");
//		try {
////			List<MultipartFile> f = ((MultipartHttpServletRequest) request).getFiles("upfile");
//			List<ResourceBO> resourceList = ((List<MultipartFile>)Collections.arrayToList(files)).stream().map(file ->ossUpload(file))
//					.collect(Collectors.toList());
////			List<Resource> resourceList = Stream.of(files).map(file ->ossUpload(file))
////					.collect(Collectors.toList());
//			ObjectCollectionResponse<ResourceBO> result = new ObjectCollectionResponse<>(0, "", resourceList);
//			return result;
//		} catch (Exception e) {
//			logger.error("图片上传出错，", e);
//			return new ObjectCollectionResponse<>(-1, "图片上传失败,请联系系统管理员");
//		}
//	}

	public ResourceBO ossUpload(MultipartFile file) {
		try {
			if (!file.isEmpty()) {
				logger.debug("file size = " + file.getSize());
				OSSClient ossClient = new OSSClient(endPoint, accessKeyId, accessKeySecret);
				ossClient.createBucket(bucketName);
				InputStream content = file.getInputStream();

				// 创建上传Object的Metadata
				ObjectMetadata meta = new ObjectMetadata();
				// 必须设置ContentLength
				meta.setContentLength(file.getSize());

				// 设置文件名
				String type = "";
				if (file.getOriginalFilename().indexOf(".") >= 0) {
					type = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
				}
				int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
				String dir = Calendar.getInstance().get(Calendar.YEAR) + "";
				if (month < 10) {
					dir += "0" + month;
				} else {
					dir += month;
				}
				String key = dir + "/" + DateUtil.date2Str(new Date(), new SimpleDateFormat("yyyyMMddHHmmssSSS"))
						+ type;

				// 上传Object.
				PutObjectResult result = ossClient.putObject(bucketName, key, content, meta);

				logger.debug("result==" + result.getETag());

				Calendar ca = Calendar.getInstance();
				ca.add(Calendar.YEAR, 100);
				ca.getTime();

				// 获得OSS服务器URL
				URL url = ossClient.generatePresignedUrl(bucketName, key, ca.getTime());
				logger.info("url:" + url);
				String strUrl = url.toString();
				content.close();
				OSSObject object = ossClient.getObject(bucketName, key);
				object.getObjectContent().close();
				// 将图片上传记录保存到本地
				if (strUrl.indexOf("?") > -1) {
					strUrl = strUrl.substring(0, strUrl.indexOf("?"));
				}
				strUrl = imgServer + strUrl.substring(strUrl.indexOf('/', 10));
				ResourceBO resource = new ResourceBO();
				resource.setUrl(strUrl);
				resource.setKey(key);
				resource.setSize(Double.valueOf(file.getSize()));
				resourceService.add(resource);
				logger.debug("生成图片上传对象" + resource);
				return resource;
			} else {
				return null;
			}
		} catch (Exception e) {
			logger.error("上传失败!",e);
			return null;
		}
	}

	// @RequestMapping(value = "/deletePic")
	// @ResponseBody
	// public String deletePic(@RequestBody JSONObject jsonObject,
	// HttpServletResponse response) {
	// logger.info("enter the oss delete method!");
	// JSONObject returnJson = new JSONObject();
	// try {
	// bucketName = sysParamService.getValue("bucketName");
	// accessKeyId = sysParamService.getValue("accessKeyId");
	// accessKeySecret = sysParamService.getValue("accessKeySecret");
	// endPoint = sysParamService.getValue("endPoint-https");
	// if (StringUtils.isNotBlank(jsonObject.getString("key"))) {
	//
	// OSSClient ossClient = new OSSClient(endPoint, accessKeyId,
	// accessKeySecret);
	// ossClient.deleteObject(bucketName, jsonObject.getString("key"));
	//
	// ossClient.shutdown();
	// }
	// } catch (Exception e) {
	// logger.error("删除图片出错，", e);
	// return null;
	// }
	// return returnJson.toJSONString();
	// }

	// @RequestMapping(value = "/download")
	// @ResponseBody
	// public JSONObject download(@RequestBody JSONObject requestJson,
	// HttpServletRequest request,
	// HttpServletResponse response) throws IOException {
	// JSONObject jsonReturn = new JSONObject();
	// bucketName = sysParamService.getValue("bucketName");
	// accessKeyId = sysParamService.getValue("accessKeyId");
	// accessKeySecret = sysParamService.getValue("accessKeySecret");
	// endPoint = sysParamService.getValue("endPoint");
	// int month = Calendar.getInstance().get(Calendar.MONTH) + 1;
	// String dir = Calendar.getInstance().get(Calendar.YEAR) + "";
	// if (month < 10) {
	// dir += "0" + month;
	// } else {
	// dir += month;
	// }
	// try {
	// logger.info(" array =" + requestJson.getJSONArray("url"));
	// logger.info("size " + requestJson.getJSONArray("url").size());
	// JSONArray array = requestJson.getJSONArray("url");
	//
	// String[] strs = new String[array.size()];
	// for (int i = 0; i < array.size(); i++) {
	// logger.info("url" + i + "=" + array.get(i).toString());
	// URL url = new URL(array.get(i).toString());
	// HttpURLConnection conn = (HttpURLConnection) url.openConnection();
	// // 设置超时间为3秒
	// conn.setConnectTimeout(3 * 1000);
	// // 防止屏蔽程序抓取而返回403错误
	// conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0;
	// Windows NT; DigExt)");
	//
	// // 得到输入流
	// InputStream inputStream = conn.getInputStream();
	// byte[] buffer = new byte[1024];
	// int len = 0;
	// ByteArrayOutputStream bos = new ByteArrayOutputStream();
	// while ((len = inputStream.read(buffer)) != -1) {
	// bos.write(buffer, 0, len);
	// }
	// bos.close();
	// // 获取自己数组
	// byte[] getData = bos.toByteArray();
	// // 文件保存位置
	// File saveDir = new File("/downloadpic");
	// if (!saveDir.exists()) {
	// saveDir.mkdir();
	// }
	// // URL根据'/'截取，获取最后一个为文件名
	// // String files[] = array.get(i).toString().split("/");
	// String fileName = DateUtil.date2Str(new Date(), new
	// SimpleDateFormat("yyyyMMddHHmmssSSS"));
	// File file = new File(saveDir + File.separator + fileName);
	// logger.info("path:" + file.getAbsolutePath());
	// FileOutputStream fos = new FileOutputStream(file);
	// fos.write(getData);
	// if (fos != null) {
	// fos.close();
	// }
	// if (inputStream != null) {
	// inputStream.close();
	// }
	//
	// OSSClient ossClient = new OSSClient(endPoint, accessKeyId,
	// accessKeySecret);
	// ossClient.createBucket(bucketName);
	// InputStream content = new FileInputStream(file);
	//
	// // 创建上传Object的Metadata
	// ObjectMetadata meta = new ObjectMetadata();
	// // 必须设置ContentLength
	// meta.setContentLength(file.length());
	//
	// // 设置文件名
	// String type = "";
	// if (file.getName().indexOf(".") >= 0) {
	// type = file.getName().substring(file.getName().indexOf("."));
	// }
	//
	// String key = dir + "/" + DateUtil.date2Str(new Date(), new
	// SimpleDateFormat("yyyyMMddHHmmssSSS"))
	// + type;
	//
	// // 上传Object.
	// PutObjectResult result = ossClient.putObject(bucketName, key, content,
	// meta);
	//
	// logger.debug("result==" + result.getETag());
	//
	// Calendar ca = Calendar.getInstance();
	// ca.add(Calendar.YEAR, 100);
	// ca.getTime();
	//
	// // 获得OSS服务器URL
	// URL urlOss = ossClient.generatePresignedUrl(bucketName, key,
	// ca.getTime());
	// logger.info("url:" + urlOss);
	// String strUrl = urlOss.toString();
	// content.close();
	// OSSObject object = ossClient.getObject(bucketName, key);
	// object.getObjectContent().close();
	//
	// if (strUrl.indexOf("?") > -1) {
	// strs[i] = strUrl.substring(0, strUrl.indexOf("?"));
	// } else {
	// strs[i] = urlOss.toString();
	// }
	// }
	// jsonReturn.put("data", strs);
	// jsonReturn.put("code", 0);
	// jsonReturn.put("msg", "成功");
	// } catch (Exception e) {
	// logger.error("图片下载上传出错：", e);
	// return null;
	// }
	// return jsonReturn;
	// }

	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getEndPoint() {
		return endPoint;
	}

	public void setEndPoint(String endPoint) {
		this.endPoint = endPoint;
	}

	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

	public String getImgServer() {
		return imgServer;
	}

	public void setImgServer(String imgServer) {
		this.imgServer = imgServer;
	}

	
	public static void main(String[] args) {
		// 1. Individual values
		Stream<String> stream = Stream.of("a", "b", "c");
		// 2. Arrays
		String [] strArray = new String[] {"a", "b", "c"};
		stream = Stream.of(strArray);
		stream = Arrays.stream(strArray);
		// 3. Collections
		List<String> list = Arrays.asList(strArray);
		stream = list.stream();
		stream.map(String::toUpperCase).forEach(System.out::println);
	}
}